package com.ebeitech.library.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ebeitech.library.R;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.ViewUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by alice on 2017/10/31.
 */
public class CommonAlertDialogFragment extends DialogFragment {

	TextView mTitleText;
	TextView mMessageText;
	Button mOkView;
	Button mCancelView;
	Button mMidView;
	TextView mProgressMessageText;
	View mViewButton;
	View mViewProgress;
	View mViewParent;
	View mViewSelect;
	TextView mSelectValue;
	ListView mListView;
	LinearLayout mCustomView;

	private Context mContext;

	private String title;
	private String message;
	private String midText;
	private String btnOkText;
	private String btnCancelText;
	private String btnMidText;
	private int messageGravity = -1;
	private String selectValue;
	private View customItemView;
	private List<String> mList = new ArrayList<String>();
	private AdapterView.OnItemClickListener onItemClickListener;
	private boolean isCancelButtonVisible = true;
	private OnBtnClickListener mOkClickListener;
	private OnBtnClickListener mCancelClickListener;
	private OnBtnClickListener mMidClickListener;
	private OnBtnClickListener mSelectClickListener;
	private DialogInterface.OnDismissListener mOnDismissListener;
	private DialogStyle mDialogStyle = DialogStyle.ALERT;
	private ListMode mListMode = ListMode.NORMAL;
	private Map<String, Boolean> mSelectMap = new HashMap<String, Boolean>();

	private BaseAdapter mAdapter;

	public interface OnBtnClickListener {
		void onClick(View v, CommonAlertDialogFragment dialog);
	}

	void onOkClick(View view) {
		if (mOkClickListener != null) {
			mOkClickListener.onClick(view, this);
		} else {
			dismiss();
		}
	}

	void onCancelClick(View view) {
		if (mCancelClickListener != null) {
			mCancelClickListener.onClick(view, this);
		} else {
			dismiss();
		}
	}

	void onMidClick(View view) {
		if (mMidClickListener != null) {
			mMidClickListener.onClick(view, this);

		} else {
			dismiss();
		}
	}

	void onSelectClick(View view) {
		if (mSelectClickListener != null) {
			mSelectClickListener.onClick(view, this);
		} else {
			dismiss();
		}
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void setButtonText(String ok , String cancel) {
		this.btnOkText = ok;
		this.btnCancelText = cancel;
	}

	public void setButtonMidText(String mid) {
		this.midText = mid;
	}

	public void setMessageGravity(int gravity) {
		messageGravity = gravity;
	}

	public void setSelectValue(String selectValue) {
		this.selectValue = selectValue;
	}

	public void updateSelectValue(String selectValue) {
		setSelectValue(selectValue);
		if (mSelectValue != null) {
			mSelectValue.setText(StringUtil.getDefaultString(selectValue));
		}
	}

	public void setCustomView(View view) {
		this.customItemView = view;
	}

	public void setList(List<String> list) {
		mList.clear();
		if (list != null && list.size() > 0) {
			mList.addAll(list);
		}
	}

	public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
		onItemClickListener = l;
	}

	public void setListMode(ListMode listMode) {
		this.mListMode = listMode;
	}

	public void setCancelButtonVisible(boolean isVisible) {
		this.isCancelButtonVisible = isVisible;
	}

	public void setOkClickListener(OnBtnClickListener okClickListener) {
		this.mOkClickListener = okClickListener;
	}

	public void setCancelClickListener(OnBtnClickListener cancelClickListener) {
		this.mCancelClickListener = cancelClickListener;
	}

	public void setMidClickListener(OnBtnClickListener midClickListener) {
		this.mMidClickListener = midClickListener;
	}

	public void setSelectClickListener(OnBtnClickListener selectClickListener) {
		this.mSelectClickListener = selectClickListener;
	}

	public void setDismissClickListener(DialogInterface.OnDismissListener dismissClickListener) {
		this.mOnDismissListener = dismissClickListener;
	}

	public DialogInterface.OnDismissListener getDismissClickListener() {
		return mOnDismissListener;
	}

	public void setStyle(DialogStyle dialogStyle) {
		this.mDialogStyle = dialogStyle;
	}

	public enum DialogStyle {
		ALERT, PROGRESS, SELECT, LIST, CUSTOM
	}

	public enum ListMode {
		NORMAL, SINGLE, OPTION
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mContext = getActivity();
		View childView = inflater.inflate(R.layout.ebei_view_message_dialog, null);
		mTitleText = childView.findViewById(R.id.tv_title);
		mMessageText = childView.findViewById(R.id.tv_message);
		mOkView = childView.findViewById(R.id.btn_ok);
		mOkView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onOkClick(v);
			}
		});
		mCancelView = childView.findViewById(R.id.btn_cancel);
		mCancelView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onCancelClick(v);
			}
		});
		mMidView = childView.findViewById(R.id.btn_mid);
		mMidView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onMidClick(v);
			}
		});
		mProgressMessageText = childView.findViewById(R.id.tv_message2);
		mViewButton = childView.findViewById(R.id.view_button);
		mViewProgress = childView.findViewById(R.id.view_progress);
		mViewParent = childView.findViewById(R.id.view_parent);
		mViewSelect = childView.findViewById(R.id.view_select);
		mViewSelect.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onSelectClick(v);
			}
		});
		mSelectValue = childView.findViewById(R.id.tv_select_value);
		mListView = childView.findViewById(R.id.view_list);
		mCustomView = childView.findViewById(R.id.view_custom);

		int margin = ViewUtil.getScreenSize((Activity) mContext).heightPixels / 6;
		childView.setPadding(0, margin, 0, margin);

		if (StringUtil.isStringNullOrEmpty(title)) {
			mTitleText.setVisibility(View.GONE);
		} else {
			mTitleText.setText(title);
			mTitleText.setVisibility(View.VISIBLE);
		}
		mMessageText.setText(message);
		mMessageText.setMovementMethod(ScrollingMovementMethod.getInstance());
		if (messageGravity > -1) {
			mMessageText.setGravity(messageGravity);
		}
		if (!StringUtil.isStringNullOrEmpty(btnOkText)) {
			mOkView.setText(btnOkText);
		}
		if (!StringUtil.isStringNullOrEmpty(btnCancelText)) {
			mCancelView.setText(btnCancelText);
		}
		if (StringUtil.isStringNullOrEmpty(midText)) {
			mMidView.setVisibility(View.GONE);
		} else {
			mMidView.setText(midText);
			mMidView.setVisibility(View.VISIBLE);
		}

		if (isCancelButtonVisible) {
			mCancelView.setVisibility(View.VISIBLE);
			mOkView.setBackgroundResource(R.drawable.ebei_dialog_btn_bg_right_selector);
		} else {
			mCancelView.setVisibility(View.GONE);
			mOkView.setBackgroundResource(R.drawable.ebei_dialog_btn_bg_left_and_right_selector);
		}

		if (mDialogStyle == DialogStyle.PROGRESS) {
			if (StringUtil.isStringNullOrEmpty(message)) {
				mProgressMessageText.setVisibility(View.GONE);
			} else {
				mProgressMessageText.setText(message);
				mProgressMessageText.setVisibility(View.VISIBLE);
			}

			mMessageText.setVisibility(View.GONE);
			mViewButton.setVisibility(View.GONE);
			mViewProgress.setVisibility(View.VISIBLE);
			mViewSelect.setVisibility(View.GONE);
			mCustomView.setVisibility(View.GONE);
			mListView.setVisibility(View.GONE);

			LinearLayout.LayoutParams lp2 = (LinearLayout.LayoutParams) mViewParent.getLayoutParams();
			lp2.width = LinearLayout.LayoutParams.WRAP_CONTENT;
			mViewParent.setLayoutParams(lp2);
		} else if (mDialogStyle == DialogStyle.SELECT){
			mMessageText.setVisibility(View.GONE);
			mViewButton.setVisibility(View.VISIBLE);
			mViewProgress.setVisibility(View.GONE);
			mViewSelect.setVisibility(View.VISIBLE);
			mCustomView.setVisibility(View.GONE);
			mListView.setVisibility(View.GONE);
			if (!StringUtil.isStringNullOrEmpty(selectValue)) {
				mSelectValue.setText(selectValue);
			}
		} else if (mDialogStyle == DialogStyle.CUSTOM){
			mMessageText.setVisibility(View.GONE);
			mViewButton.setVisibility(View.VISIBLE);
			mViewProgress.setVisibility(View.GONE);
			mViewSelect.setVisibility(View.GONE);
			mCustomView.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			if (customItemView != null) {
				mCustomView.removeAllViews();
				mCustomView.addView(customItemView,
						new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
			}
		} else if (mDialogStyle == DialogStyle.LIST){
			mMessageText.setVisibility(View.GONE);
			mViewButton.setVisibility(View.VISIBLE);
			mViewProgress.setVisibility(View.GONE);
			mViewSelect.setVisibility(View.GONE);
			mCustomView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			mSelectMap.clear();
			if (!StringUtil.isStringNullOrEmpty(selectValue)) {
				mSelectMap.put(selectValue, true);
			}
			mAdapter = new ListAdapter();
			mListView.setAdapter(mAdapter);
		} else {
			mMessageText.setVisibility(View.VISIBLE);
			mViewButton.setVisibility(View.VISIBLE);
			mViewProgress.setVisibility(View.GONE);
			mViewSelect.setVisibility(View.GONE);
			mCustomView.setVisibility(View.GONE);
		}

		if (mDialogStyle == DialogStyle.PROGRESS) {
			// 允许点击返回键返回，点击外部消失
			Dialog dialog = getDialog();
			if (dialog != null) {
				dialog.setCancelable(true);
			}

			childView.setPadding(0, 0, 0, 0);
		}
		return childView;
	}

	@Override
	public void onStart() {
		super.onStart();
		if (mDialogStyle != DialogStyle.PROGRESS) {
			Window dialogWindow = getDialog().getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			lp.width = ViewUtil.getScreenSize((Activity) mContext).widthPixels - ViewUtil.dp2px(mContext, 40);
			dialogWindow.setAttributes(lp);
		}
	}

	class ListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public String getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_text_with_check, null);
			}
			TextView textView = (TextView) convertView.findViewById(R.id.tv_name);
			ImageView checkBox = (ImageView) convertView.findViewById(R.id.iv_image);
			String name = getItem(position);
			textView.setText(name);
			if (mListMode == ListMode.SINGLE) {
				checkBox.setVisibility(View.VISIBLE);
				boolean isChecked = false;
				if (mSelectMap.get(name) != null && mSelectMap.get(name)) {
					isChecked = true;
				}
				if (isChecked) {
					checkBox.setImageResource(R.drawable.ebei_btn_list_selected);
				} else {
					checkBox.setImageResource(R.color.ebei_transparent);
				}
			} else {
				checkBox.setVisibility(View.GONE);
			}
			if (mListMode == ListMode.OPTION) {
				textView.setTextColor(getResources().getColor(R.color.ebei_blue));
				textView.setGravity(Gravity.CENTER_HORIZONTAL);
			}
			convertView.setTag(position);
			convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mListMode == ListMode.SINGLE) {
						mSelectMap.clear();
						int position = Integer.valueOf(v.getTag().toString());
						mSelectMap.put(getItem(position), true);
						notifyDataSetChanged();
					}

					if (onItemClickListener != null) {
						onItemClickListener.onItemClick(mListView, v, position, 0);
					}
				}
			});
			return convertView;
		}
	};

	/**
	 * 设置主题需要在 onCreate() 方法中调用 setStyle() 方法
	 */
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setStyle(DialogFragment.STYLE_NO_TITLE, R.style.EbeiCustomDimDialog);
		if (mDialogStyle == DialogStyle.PROGRESS) {
			setStyle(DialogFragment.STYLE_NO_TITLE, R.style.EbeiCustomDialog);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mOnDismissListener != null) {
			mOnDismissListener.onDismiss(null);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// 为了防止有时候对话框的闪退,需要注销掉这句话
		//super.onSaveInstanceState(outState);
	}

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
			onCurrentAttach(context);
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
			onCurrentAttach(activity);
		}
	}

	/**
	 * 重写此方法替代onAttach()高低版本不兼容
	 * @param mContext
	 */
	protected void onCurrentAttach(Context mContext){

	}

	public boolean isShowing(){
		return getDialog() != null && getDialog().isShowing();
	}

	@Override
	public void dismissAllowingStateLoss() {
		if (isShowing()) {
			super.dismissAllowingStateLoss();
		}
	}

	@Override
	public void show(FragmentManager manager, String tag) {
		show(manager.beginTransaction(), tag);
	}

	@Override
	public int show(FragmentTransaction transaction, String tag) {
		transaction.add(this, tag);
		int mBackStackId = transaction.commitAllowingStateLoss();
		transaction.show(this);
		return mBackStackId;
	}

	public CommonAlertDialogFragment getClone() {
		CommonAlertDialogFragment dialogFragment = new CommonAlertDialogFragment();
		dialogFragment.setTitle(title);
		dialogFragment.setMessage(message);
		dialogFragment.setStyle(mDialogStyle);
		dialogFragment.setMessageGravity(messageGravity);
		dialogFragment.setSelectValue(selectValue);
		dialogFragment.setButtonMidText(midText);
		dialogFragment.setButtonText(btnOkText, btnCancelText);
		dialogFragment.setCancelButtonVisible(isCancelButtonVisible);
		dialogFragment.setCustomView(customItemView);
		dialogFragment.setListMode(mListMode);
		dialogFragment.setList(mList);
		dialogFragment.setOkClickListener(mOkClickListener);
		dialogFragment.setCancelClickListener(mCancelClickListener);
		dialogFragment.setMidClickListener(mMidClickListener);
		dialogFragment.setSelectClickListener(mSelectClickListener);
		dialogFragment.setOnItemClickListener(onItemClickListener);
		dialogFragment.setCancelable(isCancelable());
		return dialogFragment;
	}

}
